<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    

    <meta name="baidu-site-verification" content="lt822VnP06" />
    <meta name="baidu-site-verification" content="0Ajixw1Puk" />
    <meta name="google-site-verification" content="gCQD0Y6f0YlPTZTAjp_mqms4C7TlkMWrg3Xy0mFdMwI" />
    <title>【译】以生产者消费者为例阐述如何使用wait，notify和notifyAll | Giraffe&#39;s Home</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="原文来自一个java大牛的技术博客 地址http://javarevisited.blogspot.com/2015/07/how-to-use-wait-notify-and-notifyall-in.html 博客以生产者和消费者为例 讲解了如何使用wait,notify,notifyAll进行多个线程之间的通信。下面是原文的翻译。

在Java中可以利用use,notify,notifyA">
<meta property="og:type" content="article">
<meta property="og:title" content="【译】以生产者消费者为例阐述如何使用wait，notify和notifyAll">
<meta property="og:url" content="http://yemengying.com/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/index.html">
<meta property="og:site_name" content="Giraffe's Home">
<meta property="og:description" content="原文来自一个java大牛的技术博客 地址http://javarevisited.blogspot.com/2015/07/how-to-use-wait-notify-and-notifyall-in.html 博客以生产者和消费者为例 讲解了如何使用wait,notify,notifyAll进行多个线程之间的通信。下面是原文的翻译。

在Java中可以利用use,notify,notifyA">
<meta property="og:image" content="https://pic.yupoo.com/jiananshi/599586b8/10c09844.jpg">
<meta property="og:updated_time" content="2018-12-14T09:23:02.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【译】以生产者消费者为例阐述如何使用wait，notify和notifyAll">
<meta name="twitter:description" content="原文来自一个java大牛的技术博客 地址http://javarevisited.blogspot.com/2015/07/how-to-use-wait-notify-and-notifyall-in.html 博客以生产者和消费者为例 讲解了如何使用wait,notify,notifyAll进行多个线程之间的通信。下面是原文的翻译。

在Java中可以利用use,notify,notifyA">
<meta name="twitter:image" content="https://pic.yupoo.com/jiananshi/599586b8/10c09844.jpg">
    

    

    
        <link rel="icon" href="https://yemengying.com/qiniu/image/image/favicon.png" />
    


    <link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/lib/open-sans/styles.css">
    <link rel="stylesheet" href="/lib/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/lib/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/lib/fancybox/jquery.fancybox.css">
    
    
        <script type="text/javascript">
(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-75861791-1', 'auto');
ga('send', 'pageview');

</script>
    
    
    
        <script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?44bb8bfb1a576270255713e37746eb82";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    

</head>
<body>
    <script src="//github.elemecdn.com/jiananshi/req/0.1.0/lib/req.js"></script>
    <script src="//npm.elemecdn.com/jinkela@1.2.18/umd.js"></script>
    <script src="//github.elemecdn.com/jiananshi/DisqusJS/2.0.8/index.js"></script>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">Giraffe&#39;s Home</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">归档</a>
                
                    <a class="main-nav-link" href="/categories">分类</a>
                
                    <a class="main-nav-link" href="/tags">标签</a>
                
                    <a class="main-nav-link" href="/about">关于</a>
                
                    <a class="main-nav-link" href="/message">留言</a>
                
                    <a class="main-nav-link" href="/friends">友链</a>
                
                    <a class="main-nav-link" href="/reading">正在读...</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于</a></td>
                
                    <td><a class="main-nav-link" href="/message">留言</a></td>
                
                    <td><a class="main-nav-link" href="/friends">友链</a></td>
                
                    <td><a class="main-nav-link" href="/reading">正在读...</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
            <h2 id="name">Giraffe</h2>
            <h3 id="title">Java Developer</h3>
            <span id="location"><i class="fa fa-map-marker"></i>Shanghai, China</span>
            <a id="follow" target="_blank" href="https://github.com/giraffe0813/">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                56
                <span>文章</span>
            </div>
            <div class="article-info-block">
                36
                <span>标签</span>
            </div>
        </div>
        <div class="profile-block recent-comments">
            <p class="recent-comments-title">最新评论</p>
            <ul id="disqus-recent-comments" class="recent-comments-container">
            </ul>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/giraffe0813" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            【译】以生产者消费者为例阐述如何使用wait，notify和notifyAll
        </h1>
    

                <div class="article-meta">
                    
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/">
            <time datetime="2015-10-29T06:34:55.000Z" itemprop="datePublished">2015-10-29</time>
        </a>
    </div>


                    
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/java/">java</a><i class="fa fa-angle-right"></i><a class="article-category-link" href="/categories/java/thread/">thread</a>
    </div>

                    
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/java/">java</a>, <a class="tag-link" href="/tags/翻译/">翻译</a>
    </div>

                </div>
            </header>
        
        <div class="article-entry" itemprop="articleBody">
        
            
                <div id="toc" class="toc-article">
                <strong class="toc-title">文章目录</strong>
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#在代码中展示如何使用wait和notify"><span class="toc-number">1.</span> <span class="toc-text">在代码中展示如何使用wait和notify</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在循环中使用wait和notify，而不是If代码块中"><span class="toc-number">2.</span> <span class="toc-text">在循环中使用wait和notify，而不是If代码块中</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Java中使用wait-notify-notifyAll-的例子"><span class="toc-number">3.</span> <span class="toc-text">Java中使用wait(),notify(),notifyAll()的例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用wait，notify，notifyAll需要注意的"><span class="toc-number">4.</span> <span class="toc-text">使用wait，notify，notifyAll需要注意的</span></a></li></ol>
                </div>
            
            <blockquote>
<p>原文来自一个java大牛的技术博客 地址<a href="http://javarevisited.blogspot.com/2015/07/how-to-use-wait-notify-and-notifyall-in.html" target="_blank" rel="external">http://javarevisited.blogspot.com/2015/07/how-to-use-wait-notify-and-notifyall-in.html</a> 博客以生产者和消费者为例 讲解了如何使用wait,notify,notifyAll进行多个线程之间的通信。下面是原文的翻译。</p>
</blockquote>
<p>在Java中可以利用use,notify,notifyAll来完成线程之间的通信。举个例子，假设你的程序中有两个线程(eg:<code>Producer</code>(生产者)和<code>Consumer</code>(消费者))，Producer要和Consumer通信，通知Consumer队列中有元素了可以开始消费。相似的，Consumer也需要通知Producer队列中有空闲可以插入元素了。一个线程可以可以在一定条件下调用wait方法暂停什么都不做。比如，在Producer和consumer的问题中，当队列满了时Producer需要调用wait，当队列为空时Consumer需要调用wait方法。如果一些线程在等待某些条件变为真，可以在条件改变时使用notify和notifyAll通知他们并唤醒他们。Notify方法和NotifyAll方法都可以发送通知，不同的是，notify只能向等待的线程中的一个发送通知，不保证接受到通知的是哪个线程，而NotifyAll会向所有线程发送通知。所以如果只有一个线程等待对象锁，notify和notifyAll都会通知到它。在这个java多线程的教程中，将利用生产者，消费者的例子讲述在Java中如何使用wait，notify和notifyAll实现线程内部通信。另外，如果大家对掌握多线程和并发很感兴趣，强烈建议大家阅读<code>Brian Goetz</code>写的<code>Java Concurrency in Practice</code>。如果没看过这本书，你的Java多线程之旅是不完整的🙀。</p>
<a id="more"></a>
<h3 id="在代码中展示如何使用wait和notify"><a href="#在代码中展示如何使用wait和notify" class="headerlink" title="在代码中展示如何使用wait和notify"></a>在代码中展示如何使用wait和notify</h3><p>尽管wait和notify是相当基础的概念，并且他们定义在<code>Object</code>类中，但要想在代码中使用他们并非易事。你可以在面试中让面试者通过手写代码解决Producer者和Consumer者问题来验证，我相信大多数人都会犯在错误的地方同步，没有在正确的对象上调用wait之类的错。讲真，这些常常会困惑许多程序员。第一个困惑点来自怎样调用wait方法，因为wait方法并不是定义在Thread类中，所以不能简单的Thread.wait()。而许多Java开发者习惯于Thread.sleep(),所以常常错误的想用同样的方式调用wait。实际上，wait()方法需要在一个被两个线程共享的对象上调用，例如在Producer者和消费Consumer的问题中，两个线程共享对象是一个队列。第二个困惑点来自wait方法应该在同步块还是同步方法中调用？如果使用同步块，那么哪个对象应该放到同步块中？这个对象和你想要获得锁的对象应该是同一个。在我们的例子中，这个对象就是两个线程共享的队列。<br><img src="https://pic.yupoo.com/jiananshi/599586b8/10c09844.jpg" alt="image"></p>
<h3 id="在循环中使用wait和notify，而不是If代码块中"><a href="#在循环中使用wait和notify，而不是If代码块中" class="headerlink" title="在循环中使用wait和notify，而不是If代码块中"></a>在循环中使用wait和notify，而不是If代码块中</h3><p>在你已经了解需要在一个共享的对象上调用wait方法后，接下来就是学会避免许多java开发者犯的错—在If代码块中调用wait而不是while循环中。因为需要在一定的条件下调用wait，比如Producer线程要在队列满了的情况下调用wait，所以第一反应都是使用If语句。但是，在If代码块中调用wait会产生<code>bug</code>，因为线程存在一定的可能在等待条件没有改变的情况下<code>假唤醒(spurious wake up)</code>。所以如果没有使用循环在线程唤醒后检查等待条件，可能会造成尝试在已经满了的队列中插入元素或者在空了的队列中取元素。这就是为什么我们要在while循环中调用wait而不是if。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"> <span class="comment">// The standard idiom for calling the wait method in Java</span></div><div class="line">  <span class="keyword">synchronized</span> (sharedObject) &#123;</div><div class="line">        <span class="keyword">while</span> (condition) &#123;</div><div class="line">            sharedObject.wait();<span class="comment">// (Releases lock, and reacquires on wakeup)</span></div><div class="line">         &#125; </div><div class="line">        ...<span class="comment">// do action based upon condition e.g. take or put into queue</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>正如我建议的，我们应该在一个循环中调用wait。这个循环用于在线程休眠之前和之后检查condition。</p>
<h3 id="Java中使用wait-notify-notifyAll-的例子"><a href="#Java中使用wait-notify-notifyAll-的例子" class="headerlink" title="Java中使用wait(),notify(),notifyAll()的例子"></a>Java中使用wait(),notify(),notifyAll()的例子</h3><p>下面是在Java中使用wait(),notify(),notifyAll()的例子。在这个程序中，有两个线程(PRODUCTOR和CONSUMER)，用继承了Thread类的Producer和Consumer类实现。Prodcuer和Consumer的业务逻辑写在他们各自的run()方法中。并且实现一个LinkedList，当做共享队列。Producer在一个死循环中不断在队列中插入随机数，直到队列满了。我们会检查while(queue.size == maxSize),需要注意的是在检查之前需要给队列加上同步锁以保证在检查时没有另一个线程修改队列。如果队列满了，PRODUCER线程就会休眠，直到CONSUMER消费了队列中的元素并且调用notify()方法通知PRODUCER线程。<code>wait和notify都是在共享的对象(我们的例子中是队列)上调用的</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> java.util.LinkedList;</div><div class="line"><span class="keyword">import</span> java.util.Queue;</div><div class="line"><span class="keyword">import</span> java.util.Random;</div><div class="line"><span class="comment">/**</span></div><div class="line"> * Simple Java program to demonstrate How to use wait, notify and notifyAll()</div><div class="line"> * method in Java by solving producer consumer problem.</div><div class="line"> *</div><div class="line"> * <span class="doctag">@author</span> Javin Paul</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MultipleThread</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</div><div class="line">        System.out.println(<span class="string">"How to use wait and notify method in Java"</span>);</div><div class="line">        System.out.println(<span class="string">"Solving Producer Consumper Problem"</span>);</div><div class="line">        Queue&lt;Integer&gt; buffer = <span class="keyword">new</span> LinkedList&lt;&gt;();</div><div class="line">        <span class="keyword">int</span> maxSize = <span class="number">10</span>;</div><div class="line">        Thread producer = <span class="keyword">new</span> Producer(buffer, maxSize, <span class="string">"PRODUCER"</span>);</div><div class="line">        Thread consumer = <span class="keyword">new</span> Consumer(buffer, maxSize, <span class="string">"CONSUMER"</span>);</div><div class="line">        producer.start();</div><div class="line">        consumer.start();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line"> * Producer Thread will keep producing values for Consumer</div><div class="line"> * to consumer. It will use wait() method when Queue is full</div><div class="line"> * and use notify() method to send notification to Consumer</div><div class="line"> * Thread.</div><div class="line"> * <span class="doctag">@author</span> WINDOWS 8</div><div class="line"> * */</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Producer</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> Queue&lt;Integer&gt; queue;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxSize;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Producer</span><span class="params">(Queue&lt;Integer&gt; queue, <span class="keyword">int</span> maxSize, String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(name);</div><div class="line">        <span class="keyword">this</span>.queue = queue;</div><div class="line">        <span class="keyword">this</span>.maxSize = maxSize;</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            <span class="keyword">synchronized</span> (queue) &#123;</div><div class="line">                <span class="keyword">while</span> (queue.size() == maxSize) &#123;</div><div class="line">                    <span class="keyword">try</span> &#123;</div><div class="line">                        System.out .println(<span class="string">"Queue is full, "</span> + <span class="string">"Producer thread waiting for "</span> + <span class="string">"consumer to take something from queue"</span>);</div><div class="line">                        queue.wait();</div><div class="line">                    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</div><div class="line">                        ex.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                &#125;</div><div class="line">                Random random = <span class="keyword">new</span> Random();</div><div class="line">                <span class="keyword">int</span> i = random.nextInt();</div><div class="line">                System.out.println(<span class="string">"Producing value : "</span> + i);</div><div class="line">                queue.add(i);</div><div class="line">                queue.notifyAll();</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line"> * Consumer Thread will consumer values form shared queue.</div><div class="line"> * It will also use wait() method to wait if queue is</div><div class="line"> * empty. It will also use notify method to send * notification to producer thread after consuming values</div><div class="line"> * from queue.</div><div class="line"> * <span class="doctag">@author</span> WINDOWS 8</div><div class="line"> **/</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Consumer</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> Queue&lt;Integer&gt; queue;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxSize;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Consumer</span><span class="params">(Queue&lt;Integer&gt; queue, <span class="keyword">int</span> maxSize, String name)</span></span>&#123;</div><div class="line">        <span class="keyword">super</span>(name);</div><div class="line">        <span class="keyword">this</span>.queue = queue;</div><div class="line">        <span class="keyword">this</span>.maxSize = maxSize;</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            <span class="keyword">synchronized</span> (queue) &#123;</div><div class="line">                <span class="keyword">while</span> (queue.isEmpty()) &#123;</div><div class="line">                    System.out.println(<span class="string">"Queue is empty,"</span> + <span class="string">"Consumer thread is waiting"</span> + <span class="string">" for producer thread to put something in queue"</span>);</div><div class="line">                    <span class="keyword">try</span> &#123;</div><div class="line">                        queue.wait();</div><div class="line">                    &#125; <span class="keyword">catch</span> (Exception ex) &#123;</div><div class="line">                        ex.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                &#125; System.out.println(<span class="string">"Consuming value : "</span> + queue.remove());</div><div class="line">                queue.notifyAll();</div><div class="line">            &#125;</div><div class="line"></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">Output </div><div class="line">How to use wait and notify method in Java </div><div class="line">Solving Producer Consumper Problem </div><div class="line">Queue is empty,Consumer thread is waiting <span class="keyword">for</span> producer thread to put something in queue </div><div class="line">Producing value : -<span class="number">1692411980</span> </div><div class="line">Producing value : <span class="number">285310787</span> </div><div class="line">Producing value : -<span class="number">1045894970</span> </div><div class="line">Producing value : <span class="number">2140997307</span> </div><div class="line">Producing value : <span class="number">1379699468</span> </div><div class="line">Producing value : <span class="number">912077154</span> </div><div class="line">Producing value : -<span class="number">1635438928</span> </div><div class="line">Producing value : -<span class="number">500696499</span> </div><div class="line">Producing value : -<span class="number">1985700664</span> </div><div class="line">Producing value : <span class="number">961945684</span> </div><div class="line">Queue is full, Producer thread waiting <span class="keyword">for</span> consumer to take something from queue Consuming value : -<span class="number">1692411980</span> </div><div class="line">Consuming value : <span class="number">285310787</span> </div><div class="line">Consuming value : -<span class="number">1045894970</span> </div><div class="line">Consuming value : <span class="number">2140997307</span> </div><div class="line">Consuming value : <span class="number">1379699468</span> </div><div class="line">Consuming value : <span class="number">912077154</span> </div><div class="line">Consuming value : -<span class="number">1635438928</span> </div><div class="line">Consuming value : -<span class="number">500696499</span> </div><div class="line">Consuming value : -<span class="number">1985700664</span> </div><div class="line">Consuming value : <span class="number">961945684</span> </div><div class="line">Queue is empty,Consumer thread is waiting <span class="keyword">for</span> producer thread to put something in queue</div></pre></td></tr></table></figure>
<p>为了更好的理解这个程序，我建议大家使用debug模式运行。</p>
<h3 id="使用wait，notify，notifyAll需要注意的"><a href="#使用wait，notify，notifyAll需要注意的" class="headerlink" title="使用wait，notify，notifyAll需要注意的"></a>使用wait，notify，notifyAll需要注意的</h3><ul>
<li>在Java中可以使用wait，notify，notifyAll完成多线程(不仅仅是两个线程)的内部通信。</li>
<li>在同步方法或同步块中使用wait，notify，notifyAll，否则JVM会抛出IllegalMonitorStateException</li>
<li>在循环中调用wait，notify。</li>
<li>在线程共享的对象上调用wait</li>
<li>偏向选择notifyAll，而不是notify，原因在这篇<a href="http://javarevisited.blogspot.sg/2012/10/difference-between-notify-and-notifyall-java-example.html" target="_blank" rel="external">文章</a>里</li>
</ul>
<p><img src="https://pic.yupoo.com/jiananshi/7146ee41/d4ef64f9.jpg" alt="image"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://yemengying.com/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/" data-id="cjtvbucjr004fz15shb2lks20" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    
        <a href="http://yemengying.com/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/#comments" class="article-comment-link disqus-comment-count" data-disqus-url="http://yemengying.com/2015/10/29/译-以生产者消费者为例阐述如何使用wait，notify和notifyAll/">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2015/11/01/Java-8中的扩展-Default-Defender-Extension-方法/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    【译】Java8中的扩展(default/extension)方法
                
            </div>
        </a>
    
    
        <a href="/2015/10/28/基于注解的mybatis插入对象时利用反射生成sql语句/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">使用基于注解的mybatis时,利用反射和注解生成sql语句</div>
        </a>
    
</nav>


    
    <script>
   DisqusJS.getArticleComments();
   </script>
</article>


    
    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>

</section>
            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2019 Mengying Ye<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        </div>
    </div>
</footer>
        
    
   <script>
   DisqusJS.getRecentComments(document.querySelector('#disqus-recent-comments'));
   </script>



    
        <script src="/lib/fancybox/jquery.fancybox.pack.js"></script>
    


<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>
